<template>
    <div class="container">
        <!-- 粒子背景 -->
        <canvas ref="canvas" class="canvas"></canvas>

        <!-- 表单部分 -->
        <div class="form-wrapper">
            <transition name="fade" mode="out-in">
                <div :key="isLogin ? 'login' : 'register'" class="form">
                    <h2>{{ isLogin ? '登录' : '注册' }}</h2>

                    <!-- 登录表单 -->
                    <form v-if="isLogin" @submit.prevent="login">
                        <div class="input-group">
                            <input type="email" v-model="email" placeholder="请输入邮箱" class="input-field" required />
                        </div>
                        <div class="input-group">
                            <input type="password" v-model="password" placeholder="请输入密码" class="input-field"
                                required />
                        </div>
                        <div class="btn-group">
                            <button type="submit" class="submit-btn">登录</button>
                        </div>
                        <p @click="toggleForm" class="toggle-text">没有账号？立即注册</p>
                    </form>

                    <!-- 注册表单 -->
                    <form v-if="!isLogin" @submit.prevent="register">
                        <div class="input-group">
                            <input type="email" v-model="email" placeholder="请输入邮箱" class="input-field" required />
                        </div>
                        <div class="input-group">
                            <input type="password" v-model="password" placeholder="请输入密码" class="input-field"
                                required />
                        </div>
                        <div class="input-group">
                            <input type="password" v-model="confirmPassword" placeholder="确认密码" class="input-field"
                                required />
                        </div>
                        <div class="btn-group">
                            <button type="submit" class="submit-btn">注册</button>
                        </div>
                        <p @click="toggleForm" class="toggle-text">已有账号？立即登录</p>
                    </form>
                </div>
            </transition>
        </div>

        <!-- 自定义模态框 -->
        <div v-if="showModal" class="modal">
            <div class="modal-content">
                <!-- 确保文字颜色和背景有足够的对比度 -->
                <p style="color: #333;">{{ modalMessage }}</p>
                <button @click="hideModal" class="modal-close">确定</button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';

const isLogin = ref(true);  // 控制登录与注册切换
const email = ref('');
const password = ref('');
const confirmPassword = ref('');
const canvas = ref(null);
const showModal = ref(false);
const modalMessage = ref('');

// 新增标志位，用于判断鼠标左键是否按下
const isMouseDown = ref(false);

// 切换登录/注册
const toggleForm = () => {
    isLogin.value = !isLogin.value;
};

// 邮箱验证函数
const validateEmail = (email) => {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
};

// 密码验证函数
const validatePassword = (password) => {
    const re = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,12}$/;
    return re.test(password);
};

const showCustomModal = (message) => {
    console.log('Showing modal with message:', message); // 调试信息
    modalMessage.value = message;
    showModal.value = true;
};

const hideModal = () => {
    showModal.value = false;
};

const login = () => {
    if (!validateEmail(email.value)) {
        showCustomModal('请输入有效的邮箱地址');
        return;
    }
    if (!validatePassword(password.value)) {
        showCustomModal('密码必须为 8 - 12 位数字、字母和符号的组合');
        return;
    }
    console.log('登录：', { email: email.value, password: password.value });
};

const register = () => {
    if (!validateEmail(email.value)) {
        showCustomModal('请输入有效的邮箱地址');
        return;
    }
    if (!validatePassword(password.value)) {
        showCustomModal('密码必须为 8 - 12 位数字、字母和符号的组合');
        return;
    }
    if (password.value !== confirmPassword.value) {
        showCustomModal('两次密码输入不一致');
        return;
    }
    console.log('注册：', { email: email.value, password: password.value });
};

// 发光粒子效果相关的变量
let ctx;
let particles = [];
let mouseX = 0, mouseY = 0;
const connectDistance = 150; // 连线的最大距离
const minRadius = 1;
const maxRadius = 5;

const Particle = class {
    constructor(x, y, radius, color) {
        this.x = x;
        this.y = y;
        this.radius = radius;
        this.color = color;
        this.speedX = (Math.random() - 0.5) * 2;
        this.speedY = (Math.random() - 0.5) * 2;
    }

    update() {
        // 只有鼠标左键按下时，粒子才向鼠标位置聚集
        if (isMouseDown.value) {
            // 计算与鼠标的距离
            const dx = this.x - mouseX;
            const dy = this.y - mouseY;
            const dist = Math.sqrt(dx * dx + dy * dy);

            if (dist < 150) { // 如果粒子靠近鼠标
                const force = (150 - dist) / 150; // 距离越近，力越大
                const angle = Math.atan2(dy, dx);
                this.x -= Math.cos(angle) * force * 2; // 向鼠标方向移动
                this.y -= Math.sin(angle) * force * 2;
            }
        }

        // 原本的速度运动
        this.x += this.speedX;
        this.y += this.speedY;

        // 边界检查
        if (this.x < 0 || this.x > canvas.value.width || this.y < 0 || this.y > canvas.value.height) {
            return false;
        }
        return true;
    }

    draw() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        ctx.fillStyle = this.color;
        ctx.fill();
    }
};

// 确保屏幕上有足够数量的粒子
const createParticles = (numParticles = 100) => {
    // 如果粒子数量少于设定的数量，继续生成新的粒子
    while (particles.length < numParticles) {
        const radius = minRadius + Math.random() * (maxRadius - minRadius);
        particles.push(new Particle(
            Math.random() * canvas.value.width,
            Math.random() * canvas.value.height,
            radius,
            `rgba(${Math.random() * 100 + 155}, ${Math.random() * 100 + 155}, 255, 1)`
        ));
    }
};

const drawConnections = () => {
    // 绘制粒子之间的连线
    for (let i = 0; i < particles.length; i++) {
        for (let j = i + 1; j < particles.length; j++) {
            const dx = particles[i].x - particles[j].x;
            const dy = particles[i].y - particles[j].y;
            const dist = Math.sqrt(dx * dx + dy * dy);

            if (dist < connectDistance) {
                ctx.beginPath();
                ctx.moveTo(particles[i].x, particles[i].y);
                ctx.lineTo(particles[j].x, particles[j].y);
                ctx.strokeStyle = `rgba(150, 150, 255, ${1 - dist / connectDistance})`;
                ctx.lineWidth = 1;
                ctx.stroke();
            }
        }
    }

    // 绘制鼠标与粒子的连线
    for (let i = 0; i < particles.length; i++) {
        const dx = particles[i].x - mouseX;
        const dy = particles[i].y - mouseY;
        const dist = Math.sqrt(dx * dx + dy * dy);

        if (dist < connectDistance) {
            ctx.beginPath();
            ctx.moveTo(particles[i].x, particles[i].y);
            ctx.lineTo(mouseX, mouseY);
            ctx.strokeStyle = `rgba(150, 150, 255, ${1 - dist / connectDistance})`;
            ctx.lineWidth = 1;
            ctx.stroke();
        }
    }
};

const animateParticles = () => {
    ctx.clearRect(0, 0, canvas.value.width, canvas.value.height);

    // 更新粒子并移除离开屏幕的粒子
    particles = particles.filter(particle => {
        if (!particle.update()) {
            return false; // 如果粒子需要被移除，返回 false
        }
        particle.draw();
        return true; // 如果粒子依然有效，返回 true
    });

    // 绘制连线
    drawConnections();

    // 确保屏幕上有足够的粒子
    createParticles(100);

    requestAnimationFrame(animateParticles);
};

const handleMouseMove = (event) => {
    mouseX = event.clientX;
    mouseY = event.clientY;
};

// 新增鼠标按下事件处理函数
const handleMouseDown = () => {
    isMouseDown.value = true;
};

// 新增鼠标松开事件处理函数
const handleMouseUp = () => {
    isMouseDown.value = false;
};

// 初始化粒子
const setupCanvas = () => {
    canvas.value.width = window.innerWidth;
    canvas.value.height = window.innerHeight;
    createParticles();
    animateParticles();
};

onMounted(() => {
    ctx = canvas.value.getContext('2d');
    setupCanvas();
    window.addEventListener('mousemove', handleMouseMove);
    window.addEventListener('mousedown', handleMouseDown);
    window.addEventListener('mouseup', handleMouseUp);
    window.addEventListener('resize', setupCanvas);  // 监听窗口调整大小
});

onBeforeUnmount(() => {
    window.removeEventListener('mousemove', handleMouseMove);
    window.removeEventListener('mousedown', handleMouseDown);
    window.removeEventListener('mouseup', handleMouseUp);
    window.removeEventListener('resize', setupCanvas);  // 清理事件监听
});
</script>

<style scoped>
/* 重置 html 和 body 的样式 */
html,
body {
    margin: 0;
    padding: 0;
    height: 100%;
    width: 100%;
}

/* 整个页面容器 */
.container {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 0;
    overflow: hidden;
    height: 100%;
    width: 100%;
    background: linear-gradient(135deg, #141e30 0%, #243b55 100%);
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* canvas 粒子背景 */
.canvas {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 0;
    width: 100%;
    height: 100%;
    background-color: transparent;
}

/* 表单外层样式 */
.form-wrapper {
    position: relative;
    z-index: 10;
    width: 30%;
    /* 修改宽度为屏幕宽度的 30% */
    padding: 30px;
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 12px;
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.2);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    transition: transform 0.3s ease;
}

.form-wrapper:hover {
    transform: scale(1.02);
}

/* 标题样式 */
h2 {
    text-align: center;
    font-size: 24px;
    margin-bottom: 30px;
    font-weight: bold;
    color: #99a9ff;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

/* 输入框样式 */
.input-group {
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
    /* 水平居中输入框 */
}

.input-field {
    width: 80%;
    /* 输入框宽度占父容器的 80% */
    padding: 15px;
    font-size: 16px;
    border: none;
    border-radius: 8px;
    background-color: rgba(255, 255, 255, 0.2);
    color: white;
    transition: background-color 0.3s ease;
}

.input-field::placeholder {
    color: rgba(255, 255, 255, 0.6);
}

.input-field:focus {
    outline: none;
    background-color: rgba(255, 255, 255, 0.3);
    box-shadow: 0 0 8px rgba(150, 150, 255, 0.8);
}

/* 按钮样式 */
.btn-group {
    text-align: center;
    display: flex;
    justify-content: center;
    /* 水平居中按钮 */
}

.submit-btn {
    width: 80%;
    /* 按钮宽度占父容器的 80% */
    padding: 15px;
    font-size: 18px;
    background-color: #6a11cb;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.submit-btn:hover {
    background-color: #2575fc;
    box-shadow: 0 0 12px rgba(37, 117, 252, 0.8);
}

/* 切换文本 */
.toggle-text {
    text-align: center;
    font-size: 14px;
    color: #99a9ff;
    cursor: pointer;
    margin-top: 20px;
    transition: color 0.3s ease;
}

.toggle-text:hover {
    color: #c6d0ff;
    text-decoration: underline;
}

/* 动画 */
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to {
    opacity: 0;
}

/* 自定义模态框样式 */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 20;
}

.modal-content {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    text-align: center;
}

.modal-close {
    margin-top: 10px;
    padding: 8px 16px;
    background-color: #6a11cb;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.modal-close:hover {
    background-color: #2575fc;
}
</style>